package cn.edu.tju.elm.controller;

import cn.edu.tju.core.model.HttpResult;
import cn.edu.tju.core.model.Person;
import cn.edu.tju.core.model.ResultCodeEnum;
import cn.edu.tju.core.model.User;
import cn.edu.tju.core.security.service.UserService;
import cn.edu.tju.core.utils.ObjectUtils;
import cn.edu.tju.elm.model.DeliveryAddress;
//import cn.edu.tju.elb.service.AddressService;
import cn.edu.tju.elm.repository.AddressRepository;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.amqp.RabbitConnectionDetails;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api")
@Tag(name="管理地址", description = "对配送地址的增删改查")
public class AddressController {
//    @Autowired
//    private AddressService addressService;

    @Autowired
    private UserService userService;
    @Autowired
    private AddressRepository addressRepository;

    @PostMapping("/addresses")
    @Operation(summary = "增加地址")
    public HttpResult<DeliveryAddress> addDeliveryAddress(@RequestBody DeliveryAddress deliveryAddress) {
//        User user = userService.getUserWithAuthorities().get();
//        DeliveryAddress newDeliveryAddress = new DeliveryAddress();
//        ObjectUtils.newObjectDefaultInit(newDeliveryAddress, user);
//        newDeliveryAddress.setContactName(deliveryAddress.getContactName());
//        newDeliveryAddress.setContactTel(deliveryAddress.getContactTel());
//        newDeliveryAddress.setAddress(deliveryAddress.getAddress());
//        newDeliveryAddress.setCustomer(user);
//      /*  // 顾客可能自己希望设置性别，因此不硬性设置用户性别
//        Person person = (Person) user;
//        // 性别设置为 0男士 1女士
//        newDeliveryAddress.setContactSex(deliveryAddress.getContactSex() == null ? ("男".equals(person.getGender()) ? 0 : 1) : deliveryAddress.getContactSex());*/
//        return HttpResult.success(addressRepository.save(newDeliveryAddress));
            User user = userService.getUserWithAuthorities().get();
            DeliveryAddress newDeliveryAddress = new DeliveryAddress();

            // 关键改进1：确保所有必填字段被正确设置
            newDeliveryAddress.setContactName(deliveryAddress.getContactName());
            newDeliveryAddress.setContactTel(deliveryAddress.getContactTel());
            newDeliveryAddress.setAddress(deliveryAddress.getAddress());
            newDeliveryAddress.setCustomer(user);

            DeliveryAddress savedAddress = addressRepository.save(newDeliveryAddress);
            return HttpResult.success(savedAddress);


    }


    @GetMapping("/addresses")
    @Operation(summary="返回当前用户地址",method = "GET")
    public HttpResult  getAllDeliveryAddressByUserId(@RequestParam Long userId) {
        try {
            // 获取当前登录用户（根据您的安全框架调整）

            User user = userService.getUserWithAuthorities().get();
            // 根据用户ID查询所有地址
            List<DeliveryAddress> addresses = addressRepository.findDeliveryAddressByCustomerId(user.getId());

            return HttpResult.success(addresses);

        } catch (RuntimeException e) {
            return HttpResult.failure(ResultCodeEnum.NOT_FOUND, e.getMessage());
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SYSTEM_ERROR, "系统错误");
        }
    }

    @DeleteMapping("/addresses/{id}")
    @Operation(summary = "删除地址")
    public HttpResult<Void> deleteDeliveryAddress(@PathVariable Long id) {
        try {
            // 1. 获取当前用户
            User currentUser = userService.getUserWithAuthorities()
                    .orElseThrow(() -> new RuntimeException("用户未登录"));

            // 2. 查询要删除的地址
            DeliveryAddress address = addressRepository.findById(id)
                    .orElseThrow(() -> new RuntimeException("地址不存在"));

            // 3. 权限验证：只能删除自己的地址
            if (!address.getCustomer().getId().equals(currentUser.getId())) {
                return HttpResult.failure(ResultCodeEnum.NOT_AUTHORIZED, "无权删除此地址");
            }

            // 4. 执行删除
            addressRepository.deleteById(id);

            return HttpResult.success();

        } catch (RuntimeException e) {
            return HttpResult.failure(ResultCodeEnum.NOT_FOUND, e.getMessage());
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SYSTEM_ERROR, "删除失败: " + e.getMessage());
        }
    }




    @PatchMapping("/addresses/{id}")
    @Operation(summary = "修改地址信息")
    public HttpResult<DeliveryAddress> updateDeliveryAddress(
            @PathVariable Long id,
            @RequestBody DeliveryAddress updateDto) {
        try {
            // 1. 获取当前用户
            User currentUser = userService.getUserWithAuthorities()
                    .orElseThrow(() -> new RuntimeException("用户未登录"));

            // 2. 查询要修改的地址
            DeliveryAddress existingAddress = addressRepository.findById(id)
                    .orElseThrow(() -> new RuntimeException("地址不存在"));

            // 3. 权限验证：只能修改自己的地址
            if (!existingAddress.getCustomer().getId().equals(currentUser.getId())) {
                return HttpResult.failure(ResultCodeEnum.NOT_AUTHORIZED, "无权修改此地址");
            }

            // 4. 部分更新字段（只更新传入的字段）
            if (updateDto.getContactName() != null) {
                existingAddress.setContactName(updateDto.getContactName());
            }
            if (updateDto.getContactTel() != null) {
                existingAddress.setContactTel(updateDto.getContactTel());
            }
            if (updateDto.getAddress() != null) {
                existingAddress.setAddress(updateDto.getAddress());
            }

            // 5. 保存更新
            DeliveryAddress updatedAddress = addressRepository.save(existingAddress);
            return HttpResult.success(updatedAddress);

        } catch (RuntimeException e) {
            return HttpResult.failure(ResultCodeEnum.NOT_FOUND, e.getMessage());
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SYSTEM_ERROR, "更新失败: " + e.getMessage());
        }
    }

}
